/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import domain.pojo.User;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import util.HibernateUtil;

/**
 *
 * @author lion
 */
public class UserDaoImpl extends UserDao {

    private Session session = null;

    public UserDaoImpl() {
        session = HibernateUtil.getSessionFactory().openSession();
    }

    @Override
    public List<User> getUsers() {
        Transaction transaction = null;
        try {
            transaction = session.beginTransaction();
            List<User> users = session.createQuery("from User").list();
            transaction.commit();
            return users;
        } catch (HibernateException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public User getUser(int userId) {
        Transaction transaction = null;
        try {
            transaction = session.beginTransaction();
            User user = (User) session.get(User.class, userId);
            transaction.commit();
            return user;
        } catch (HibernateException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Integer insertUser(User user) {
        Transaction transaction = null;
        Integer userId = null;
        try {
            transaction = session.beginTransaction();
            userId = (Integer) session.save(user);
            transaction.commit();
        } catch (HibernateException e) {
            e.printStackTrace();
        }
        return userId;
    }

    @Override
    public boolean updateUser(User user) {
        Transaction transaction = null;
        boolean result = false;
        try {
            transaction = session.beginTransaction();
            session.update(user);
            transaction.commit();
            result = true;
        } catch (HibernateException e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public boolean deleteUser(User user) {
        Transaction transaction = null;
        boolean result =  false;
        try {
            transaction = session.beginTransaction();
            session.delete(user);
            transaction.commit();
            result = true;
        } catch (HibernateException e) {
            e.printStackTrace();
        }
        return result;
    }

}
